<template>
	<view class="uni-page">
		<view class="header-btn">
			<view class="zd">
				<button type="primary" size="mini" @click="openDrawer">一键下单</button>
				<!-- <button type="primary" size="mini" @click="openDrawer">手动下单</button> -->
			</view>
		</view>
		<view class="token-list">
			<!-- 	<view class="token-item"
				:class="[tokenId.tkno == item.tkno ? 'token-active' : '', item.kycs > 0 ? '' : 'token-active-no']"
				v-for="item in tokens" :key="item.id">
				{{item.tkno}}
			</view> -->
			<uni-table ref="table" border stripe type="selection" emptyText="暂无更多数据"
				@selection-change="selectionChange">
				<uni-tr>
					<uni-th align="center">token</uni-th>
				</uni-tr>
				<uni-tr v-for="(item, index) in tokens" :key="index">
					<uni-td>
						<view class="name"
							:class="[tokenId.tkno == item.tkno ? 'token-active' : '', item.kycs > 0 ? '' : 'token-active-no']">
							{{ item.tkno }}
						</view>
					</uni-td>

				</uni-tr>
			</uni-table>
		</view>
		<view class="auto-setting">
			<uni-section title="宝贝类型" type="line">
				<view class="uni-px-5 uni-pb-5">
					<uni-data-checkbox multiple v-model="type" :localdata="type_value"></uni-data-checkbox>
				</view>
			</uni-section>
			<uni-section title="浏览宝贝" type="line" padding style="display: flex;">
				<uni-number-box :value="1" />~<uni-number-box :value="4" />秒
			</uni-section>
			<uni-section title="浏览店铺" sub-title="浏览：" type="line" padding style="display: flex;">
				<uni-number-box :value='2' />~ <uni-number-box :value='5' />秒
			</uni-section>
			<uni-section title="浏览店铺" type="line" sub-title="" padding style="display: flex;">
				货比：<uni-number-box :value="3" />浏览：
				<uni-number-box :value="3" />~<uni-number-box :value='5' />秒
			</uni-section>
			<uni-section title="销量 " type="line" padding style="display: flex; ">
				<uni-number-box :value='1000' :max="5000" />：单以下不下单
			</uni-section>
			<uni-section title="价格区间 " type="line" padding style="display: flex; ">
				<uni-number-box :value="15" />~<uni-number-box :value='22' />元
			</uni-section>
			<uni-section title="下单方式 " type="line" padding style="display: flex; ">
				<uni-data-select v-model="value" :localdata="range"></uni-data-select>
			</uni-section>
			<uni-section title="收藏选择 " type="line" padding style="display: flex; ">
				<uni-data-checkbox :value="0" :localdata="sex"></uni-data-checkbox>
			</uni-section>
			<uni-section title="sku选择 " type="line" padding style="display: flex; ">
				<uni-data-checkbox :value="1" :localdata="sku"></uni-data-checkbox>
			</uni-section>
			<uni-section title="随机修改名称" type="line">
				<view class="uni-px-5 uni-pb-5">
					<uni-data-checkbox v-model="value" :localdata="good_name"></uni-data-checkbox>
				</view>
			</uni-section>
		</view>
		<uni-drawer ref="drawer" mode="right" :width="320">
			<view class="scroll-view">
				<scroll-view class="scroll-view-box" scroll-y="true">
					<view class="auto-header">
						<view class="control-btn">
							<button type="primary" size="mini" :loading="autoOrderLoading" v-if="userinfo.zidongxd == 1"
								@click="isAutoOrder ? onAutoStartOrder() : onAutoStopOrder()">{{isAutoOrder?'开始自动下单':'停止自动下单'}}</button>
						</view>

					</view>
					<view class="static">
						总 {{ tokenTotal }} 电商账号，当前执行第 {{ tokenExec }} 个，已下单 {{ tokenFinish }} 单
					</view>
					<!-- 			<view class="">
						<slider :value="tokenPercent" @change="sliderChange" show-value />
					</view> -->
					<view class="log" v-html="stepByStep">

					</view>

				</scroll-view>
			</view>
		</uni-drawer>
	</view>
</template>

<script setup>
	import {
		useEnableToken,
		useMemberStore
	} from '@/stores';
	import {
		computed,
		reactive,
		ref
	} from 'vue';
	import {
		createOrderAPI
	} from '../../apis/order';
	const enableToken = useEnableToken()
	const memberStore = useMemberStore()
	const userinfo = ref(memberStore.profile)
	// console.log('userinfo', userinfo.value);
	const tokens = ref(enableToken.token.data.drchenggong)
	const type_value = ref([{
			text: '退货包邮',
			value: 0
		}, {
			text: '刷新黑名单',
			value: 1
		}, {
			text: '七天无理由退货',
			value: 2
		},
		{
			text: '屏蔽同省商家',
			value: 3
		},
	])
	const good_name = ref([{
		text: '随机名称修改',
		value: 0
	}])
	const value = 0
	const range = ref([{
			value: 0,
			text: "随机选择(开团/拼团)"
		},
		{
			value: 1,
			text: "开团"
		},
		{
			value: 2,
			text: "拼团"
		},
	])
	const sex = ref([{
		text: '店铺',
		value: 0
	}, {
		text: '商品',
		value: 1
	}])
	const sku = ref([{
		text: '最低Sku',
		value: 0
	}, {
		text: '随机Sku',
		value: 1
	}])
	const type = ref([0, 1, 2, 3])
	const start = ref(1)
	const end = ref(4)

	const tokenId = ref({
		shipAddr: {}
	})
	const isAutoOrder = ref(true)
	const autoOrderLoading = ref(false)
	const tokenExec = ref(0) //执行到第多少token
	const isXiaDan = ref(0) //正在下单状态
	const cishu = ref(0)
	const jsid = ref(0)
	//暂存下单次数
	const tokenCount = ref(0)
	// 下单次数
	const orderFreq = ref(2)
	//开始下单步进html
	const stepByStep = ref('')
	const autoTokenCount = ref(-1)
	//已下单数量
	const tokenFinish = ref(0)
	//电商账号总数
	const tokenTotal = ref(0)
	// 选择下标
	const selectedIndexs = ref([])
	const tokenPercent = computed(() => {

		return tokenExec.value ? parseInt((tokenExec.value / tokenTotal.value) * 100) : 0
	})
	// 选择数据 
	const selectionChange = ((e) => {

		selectedIndexs.value = e.detail.index
		// console.log('选择的数据', selectedIndexs.value);
	})
	const selectedItems = (() => {
		// console.log(selectedIndexs.value);
		return selectedIndexs.value.map(i => tokens.value[i])
	})
	// 开始下单
	const onAutoStartOrder = (() => {
		let tokenItems = selectedItems()
		if (tokenItems.length < 1) {
			uni.showModal({
				title: '提示',
				content: '请至少选择一个Token'
			})
			return
		}
		autoOrderLoading.value = true
		isAutoOrder.value = false
		//点击开始自动如果正在执行数为0 则将当前正在执行改为1
		tokenExec.value == 0 && (tokenExec.value = 1)

		//获取token列表

		const tokenList = [] //存储未下单的token
		let tokenIdList = []
		// console.log('tokenItems', tokenItems);

		// 总数
		tokenTotal.value = tokenItems.length
		// console.log('tokenTotal', tokenItems);
		for (let i = 0; i < tokenItems.length; i++) { //收集下单数量，已下单的不在收集
			if (tokenItems[i].kycs != 0) {
				tokenIdList.push(tokenItems[i].id)
				for (let j = 0; j < tokenItems[i].kycs; j++) {

					tokenList.push(tokenItems[i])
				}
			}
		}

		// //如果token列表中的订单都已经下完  用户点击自动开始下单则中断下单
		if (tokenList.length == 0) {
			uni.showToast({
				title: '暂无可下单的token',
				icon: 'none'
			})
			autoOrderLoading.value = !1 //移除下单加载状态
			isAutoOrder.value = !0 //自动下单按钮改为
			return
		}

		setTimeout(() => {
			// console.log('执行');
			isXiaDan.value = 1 //开启下单状态
			autoOrderLoading.value = !1
			autoRecursion(tokenList.length, tokenList, cishu.value, jsid.value, jsid.value ? '' :
				tokenIdList)
		}, 1000)
	})
	const random = ((lower, upper) => {
		return Math.floor(Math.random() * (upper - lower + 1)) + lower;
	})
	// 时间阻塞
	const sleep = time => {
		return new Promise(resolve => {
			setTimeout(resolve, time)
		})
	}
	// 执行方法
	const autoRecursion = (async (num, tokenList, cishu, jsid, tokenIdList) => {

		let tokenId = tokenList[tokenList.length - num].id,
			tokenCode = tokenList[tokenList.length - num].tkno,
			tokenItem = {} //
			,
			orderCount = 0 //记录token号第几次下单
		// console.log('第' + num + '次', tokenList);
		tokenCount.value == 2 && (tokenCount.value = 0) //下单次数等于2时改为0

		for (let i = 0; i < tokens.value.length; i++) {
			if (tokens.value[i].id === tokenId) {
				orderCount = orderFreq.value - (tokens.value[i].kycs - 1) //自动下单显示的已下单次数
				tokenItem = tokens.value[i] //将筛选出的tokenItem保存，在订单下完后减去可用次数
			}
		}
		// console.log(tokenCount);
		num--
		autoTokenCount.value++ //自动下单次数，用于暂停自动下单

		await sleep(1500)
		// scrollBottom()
		if (autoTokenCount.value == -1) return
		stepByStep.value +=
			`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]自动切换IP中</view>`

		await sleep(1500)
		// scrollBottom()
		if (autoTokenCount.value == -1) return
		stepByStep.value +=
			`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]IP修改成功，IP地址*.*.${random(1, 255)}.${random(1, 255)}</view>`

		await sleep(2500)
		// scrollBottom()
		if (autoTokenCount.value == -1) return
		stepByStep.value +=
			`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]账号正常开始任务</view>`

		await sleep(2500)
		// scrollBottom()
		if (autoTokenCount.value == -1) return
		stepByStep.value +=
			`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]模拟搜索翻页</view>`

		await sleep(6000)
		// scrollBottom()
		if (autoTokenCount.value == -1) return
		stepByStep.value +=
			`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]浏览宝贝</view>`

		await sleep(2300)
		// scrollBottom()
		if (autoTokenCount.value == -1) return
		stepByStep.value +=
			`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]浏览店铺</view>`

		await sleep(2300)
		// scrollBottom()
		if (autoTokenCount.value == -1) return
		stepByStep.value +=
			`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]选中商品</view>`

		await sleep(2300)
		// scrollBottom()
		if (autoTokenCount.value == -1) return
		stepByStep.value +=
			`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]收藏宝贝</view>`

		await sleep(2300)
		// scrollBottom()
		if (autoTokenCount.value == -1) return
		stepByStep.value +=
			`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]随机修改呢称</view>`

		await sleep(2300)
		// scrollBottom()
		if (autoTokenCount.value == -1) return
		stepByStep.value +=
			`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]正在选宝sku拼单</view>`

		await sleep(2500)
		// scrollBottom()
		if (autoTokenCount.value == -1) return
		stepByStep.value +=
			`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]正在通信付款</view>`
		console.log('请求api', tokenIdList);
		console.log('tokenIdList', tokenIdList);
		//ajax
		let data = await createOrderAPI({
			cishu: cishu.value ? cishu.value + 1 : 0,
			jsid: jsid.value ? jsid.value : 0,
			tokenliststr: tokenIdList ? tokenIdList.join(',') : '',
			tkid: tokenId
		})
		if (0 == data.code) {
			uni.showModal({
				title: '提示',
				content: data.msg
			})
			isXiaDan.value = 0 //关闭下单状态
			autoOrderLoading.value = !1 //关闭按钮加载状态
			isAutoOrder.value = !0 //自动提现按钮禁用状态移除
			//自动下单停止后进度条退回
			progressBack()
			return
		}

		if (1 == data.code) {
			await sleep(6000)
			stepByStep.value +=
				`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]通信正常，正常付款</view>`
			// scrollBottom()

			await sleep(2000)
			stepByStep.value +=
				`<view class="mb-2">第${orderCount}次下单[${tokenCode}-${new Date().getTime()}]付款成功商品名：${data.data.goodname}, 商品价格：${data.data.price}, 手续费：${data.data.shouxufei}, 手续费率：${data.data.feilv}</view>`
			// scrollBottom()

			// getUserInfo()
			// $set(tokenItem, 'kycs', tokenItem.kycs - 1) //设置当前选中的token下单次数-1
			tokenItem.kycs = tokenItem.kycs - 1 //设置当前选中的token下单次数-1
			// console.log(tokenItem);
			tokenItem.isVerify = 1 //开启自动下单后将所有是否验证 设置为已验证
			tokenItem.shipAddr = {
				name: 1,
				mobile: 1,
				area: 1,
				dizhi: 1,
				youbian: 1
			} //将所有token地址填写填为已填写
			tokenCount.value = orderFreq.value - tokenItem.kycs //显示token可用次数
			// console.log('tokenCount', tokenCount);
			//保存后台要求参数
			cishu = data.data.dcishu
			jsid = data.data.jsid

			//下单次数
			tokenFinish.value++ //每下一单+1

			//正在执行第多少个token
			// progressAdvance()

			await sleep(500)
			// scrollBottom()
			if (autoTokenCount.value == -1) return

			// console.log('第二次', tokenList);
			if (num != 0) autoRecursion(num, tokenList, data.data.cishu, data.data.jsid, tokenIdList)
			console.log('是否下单完成', num);
			if (num == 0) { // 递归完成
				isXiaDan.value = 0; // 将正在下单状态 改为未下单
				autoTokenCount.value = -1; // 自动下单次数 //改为-1
				isAutoOrder.value = !0 // 开始/停止自动下单 状态初始化
				cishu.value = 0 //次数
				jsid.value = 0 //jsid
				uni.showToast({
					title: '成功',
					duration: 0,
					message: '自动下单任务已执行完成',
					type: 'success'
				});
			}
		}
	})
	//停止自动下单

	const onAutoStopOrder = (() => {
		autoTokenCount.value = -1 //计数改为-1
		isAutoOrder.value = !0 //自动下单停止
		isXiaDan.value = 0 //关闭下单状态

		//自动下单停止后进度条退回
		// progressBack()
	})
	// 进度条前进
	const progressAdvance = (() => {
		let tokenNo = 0,
			tokenLen = tokens.value.length
		for (let i = 0; i < tokenLen; i++) {
			if (tokens.value[i].kycs == 0) {
				tokenNo++
			}
		}
		tokenExec.value = tokenNo != tokenLen ? tokenNo + 1 : tokenLen
	})
	// 进度条退回
	const progressBack = () => {
		let tokenNo = 0,
			tokenLen = tokenItems.value.length
		for (let i = 0; i < tokenLen; i++) {
			if (tokenItems.value[i].kycs == 0) {
				tokenNo++
			}
		}
		tokenExec.value = tokenNo
	}

	// 自动下单结束
	const drawer = ref(null)
	const openDrawer = (() => {
		drawer.value.open()
	})
</script>

<style lang="scss">
	.uni-page {
		padding: 20upx;

		.header-btn {
			.zd {
				display: flex;
				justify-content: space-around;
			}

			margin-bottom: 20upx;
		}

		.auto-setting {
			padding-top: 20upx;
		}

		.auto-header {
			padding: 20upx;
			display: flex;
			justify-content: space-between;
		}

		.scroll-view-box {
			flex: 1;
			position: absolute;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
		}

		.log {

			::v-deep .mb-2 {
				margin-bottom: 10upx;
				color: #f60;
				display: flex;
			}

			// height: 100upx;

			padding: 20upx;
		}



		.token-list {
			border: 1px solid #ddd;
			height: 500upx;
			overflow: scroll;
			border-radius: 10upx;

			.token-item {
				padding: 5upx;
			}

			.token-active-no,
			.token-active-no:hover {
				background-color: #fef0f0;
				color: #f56c6c;
			}
		}
	}
</style>